library('ggplot2')

# uses norm for the fit test
# e.g.
# best_lambdas('paiva','0',12)

best_lambdas <- function(filename, state, maxmem, fit_test=test.distance, best_fit=min, simple=FALSE)
{
	curvesdistance <- c()
	if(identical(fit_test,test.distance))
		ylab <- bquote(max(abs(X[lambda] - italic(D))))
	df <- NULL
	X <- read(filename)
	for(m in 1:maxmem) {
		s <- paste(rep(state,m), collapse='')
		Y <- Xstate(X, s)
		r <- find_lambda(Y, pnorm, fit_test, best_fit)
		r. <- r
		df <- rbind(df, data.frame(lambda=r$lambda, norm=r$fit, distribution='N(0,1)', memory=m))
		r <- find_lambda(Y, pbhp, fit_test, best_fit)
		df <- rbind(df, data.frame(lambda=r$lambda, norm=r$fit, distribution='BHP', memory=m))
		curvesdistance <- c(curvesdistance, abs(r.$lambda - r$lambda))
	}
	print(paste("curves distance in median:", median(curvesdistance)))

	p <- ggplot(data=df, aes(x=lambda, y=norm, group=distribution, colour=distribution, size=memory)) +
		geom_path() + geom_point(shape=21, fill='white')
	if(!simple)
		p <- p + labs(x=expression(lambda^'*'), y=ylab) + ggtitle(paste(filename, c('-','+')[strtoi(state)+1]))
		# c('\u2198','\u2197')
	p
}

